package yana.tpe.onlineshop.controller;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yana.tpe.onlineshop.domain.domains.Category;
import yana.tpe.onlineshop.domain.domains.Product;
import yana.tpe.onlineshop.services.CategoryService;
import yana.tpe.onlineshop.services.ProductService;

/**
 *
 */
public class AbstractController {
    public static final String ADD = "/add";
    public static final String ADMIN = "/admin";
    public static final String CATEGORY = "/category";
    public static final String CATEGORY_ID = "categoryId";
    public static final String CHILD = "/{child}";
    public static final String DELETE = "/delete";
    public static final String ID = "/{id}";
    public static final String PRODUCT = "/product";
    public static final String ROOT_NAME = "root";
    public static final String UPDATE = "/update";
    public static final String COMMENT = "/comment";
    public static final String ROOT = "/" + ROOT_NAME;
    
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected Integer extractIntegerId(String id) throws NumberFormatException {
        if (ROOT_NAME.equals(id)) {
            return null;
        }
        if (id != null && !id.trim().isEmpty()) {
            return Integer.parseInt(id);
        } else {
            return null;
        }
    }

    protected Category getCategory(CategoryService categoryService, String id) throws NumberFormatException {
        return categoryService.get(extractIntegerId(id));
    }

    protected String getCategoryId(Category category) {
        return category != null && category.getId() != null ? category.getId().toString() : ROOT_NAME;
    }

    protected Product getProduct(ProductService productService, String id) throws NumberFormatException {
        Product product = productService.get(Integer.parseInt(id));
        if (product == null) {
            product = new Product();
        }
        return product;
    }
    
    protected String getRedirectBaseUrl(HttpServletRequest request, String base) {
        String requestURI = request.getRequestURI();
        int indexOf = requestURI.indexOf(base);
        if (indexOf != -1) {
            requestURI = requestURI.substring(0, indexOf + base.length());
        }
        String name = "redirect:" + requestURI;
        logger.debug("base redirect is [{}]", name);
        return name;
    }
    
}
